package cn.hou.redis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.Test;

import redis.clients.jedis.Jedis;

/**
 * 测试API
 */
public class Test02 {
	
	private Jedis jedis;
	
	//获取jedis对象
	public static Jedis getJedis() {
		Jedis jedis=new Jedis("192.168.133.128",6379);
		//jedis.auth("123456");
		return jedis;
	}
	
	//key
	@Test
	public void test01(){
		jedis=getJedis();
		//获取所有key
		Set<String> set=jedis.keys("*");
		for (String string : set) {
			System.out.println(string);
		}
		System.out.println(jedis.exists("money"));
		System.out.println(jedis.ttl("money"));
		
	}
	//String
	@Test
	public void test02(){
		jedis=getJedis();
		//set与get
		jedis.set("k1", "v1");
		System.out.println(jedis.get("k1"));
		//多个set与get
		System.out.println(jedis.mset("k2","v2","k3","v3"));
		System.out.println(jedis.mget("k1","k2","k3"));
		//设置过期时间
		System.out.println(jedis.setex("k4", 10, "v4"));
		//不覆盖set,即存在set不成功
		System.out.println(jedis.setnx("k4", "hahah"));
		//替换,将k1的第一个字符替换成alue
		System.out.println(jedis.setrange("k1", 1, "alue"));
		System.out.println(jedis.get("k1"));
		//取指定字符串,-1表示最后
		System.out.println(jedis.getrange("k1", 0, -1));
		//加减
		jedis.set("num", "1");
		System.out.println(jedis.incr("num"));//加一
		System.out.println(jedis.incrBy("num", 5));//加5.减同样
	}
	//List
	@Test
	public void test03(){
		jedis=getJedis();
		//添加
		jedis.lpush("list01", "1","2","3");//从左进栈
		jedis.rpush("list02", "1","2","3");//从右进栈
		//获取
		List<String> list01 = jedis.lrange("list01", 0, -1);
		for (String string : list01) {
			System.out.println(string);
		}
	}
	//Set
	@Test
	public void test04(){
		jedis=getJedis();
		jedis.sadd("set01", "2","2","1");
		Set<String> set01 = jedis.smembers("set01");
		for (String string : set01) {
			System.out.println(string);
		}
		jedis.srem("set01","1");
		System.out.println(jedis.smembers("set01").size());
	}
	//Hash
	@Test
	public void test05(){
		jedis=getJedis();
		jedis.hset("hash1","userName","lisi");
	    System.out.println(jedis.hget("hash1","userName"));
	    Map<String,String> map = new HashMap<String,String>();
	    map.put("telphone","13811814763");
	    map.put("email","abc@163.com");
	    map.put("address","atguigu");
	    jedis.hmset("hash02",map);
	    List<String> hash = jedis.hmget("hash02","telphone","email");
	    for (String string : hash) {
		       System.out.println(string);
	    }
	}
	//Zset
	@Test
	public void test06(){
		jedis=getJedis();
		jedis.zadd("zset01",60d,"v1");
		jedis.zadd("zset01",70d,"v2");
		jedis.zadd("zset01",80d,"v3");
		jedis.zadd("zset01",90d,"v4");
		Set<String> s1 = jedis.zrange("zset01",0,-1);
		for (String string : s1) {
			System.out.println(string);
		}
		
	}
}
